package com.project.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;

public class MyJWT {
    /**
     * 创建jwt
     *
     * @param userid
     * @param username
     * @param issuer
     * @param expire   单位为秒
     * @return
     * @throws IllegalArgumentException
     * @throws UnsupportedEncodingException
     */
    public static String createJwt(Integer userid, String username, String issuer, String secretKey, Integer expire) throws IllegalArgumentException, UnsupportedEncodingException {
        Algorithm al = Algorithm.HMAC256(secretKey);
        String token = com.auth0.jwt.JWT.create()
                .withIssuer(issuer)
                .withSubject(username)
                .withClaim("userid", userid)
                .withExpiresAt(new Date(System.currentTimeMillis() + 100 * expire))
                .sign(al);
        return token;
    }

    /**
     * 验证jwt
     */
    public static Boolean verifyJwt(String token,String secretKey) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secretKey);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (IllegalArgumentException e) {
//            e.printStackTrace();
            return false;
        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
            return false;
        } catch (JWTVerificationException e) {
//            e.printStackTrace();
            return false;
        }
    }

}
